<?php
defined('IN_APPS') or die('No direct access zura!');

// load UserModel file
require_once MODEL_PATH . DS . 'user_model.php';

/**
 * Frontpage controller
 */  
class User extends Controller {
	
	/**
	 * Default action for controller. We will use this action to list all the blog posts	 
	 */	 	
	public function index()
	{
		if (!$this->isAdmin()) {
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'You are not allowed here!', 'error');
		}
		
		
		// load smarty from our global variable
		global $view;
		
		// create UserModel instance
		$userModel = new UserModel();
		
		// load all users
		$users = $userModel->getAll();
		
		// set page title
		$view->assign('title', 'User List : ' . $this->title);
		
		// assign the $users array to the view
		$view->assign('users',	$users);
		
		// load the view file
		$view->display('user.index.php');
	}
	
	
	/**
	 * Show add user form
	 */	 	
	public function add()
	{
		if (!$this->isAdmin()) {
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'You are not allowed here!', 'error');
		}
		
		// load smarty from our global variable
		global $view;
		
		// set page title
		$view->assign('title', 'Add New User : ' . $this->title);
		
		// load the view file
		$view->display('user.add.php');
	}
	
	
	/**
	 * Show edit user form
	 */	 	
	public function edit($id)
	{
		// Make sure ID is integer
		if (!is_integer($id)) {
			// proceed
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'Invalid ID!', 'error');
		}
		
		
		if (!$this->isAdmin()) {
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'You are not allowed here!', 'error');
		}
		
		// load smarty from our global variable
		global $view;
		
		// create UserModel instance
		$userModel = new UserModel();
		
		// get user details so we can populate it in our form
		$user = $userModel->get($id);
		
		// assign it to our view
		$view->assign('user', $user);
		
		// set page title
		$view->assign('title', 'Add New User : ' . $this->title);
		
		// load the view file
		$view->display('user.edit.php');
	}
	
	
	
	/**
	 * Show user info
	 */	 	
	public function view($args)
	{
		$id = 0;
		
		// if user pass array
		if (is_array($args)) {
			
			$id = $args['id'];
			
			pr($args, true);
			exit;
		}
		
		// Make sure ID is integer
//		if (!is_integer($id)) {
//			// proceed
//			redirect(
//					array(
//						'controller'	=> 'frontpage',
//						'action'		=> 'index'
//						), 'Invalid ID!', 'error');
//		}
		
		$security = new Security();
		
		$id = $security->xss_clean($id);
		
		// load smarty from our global variable
		global $view;
		
		// create UserModel instance
		$userModel = new UserModel();
		
		// get user details so we can populate it in our form
		$user = $userModel->get($id);
		
		$user['firstname']	= stripslashes($user['firstname']);
		$user['lastname']	= stripslashes($user['lastname']);
		$user['email']		= stripslashes($user['email']);
		$user['no_telefon']	= stripslashes($user['no_telefon']);
		$user['jantina']	= stripslashes($user['jantina']);
		
		// assign it to our view
		$view->assign('user', $user);
		
		// set page title
		$view->assign('title', $user['firstname'] . ' ' . $user['lastname'] . ' : ' . $this->title);
		
		// load the view file
		$view->display('user.view.php');
	}
	
	
	/**
	 * Create new user
	 */
	public function create()
	{
		if (!$this->isAdmin()) {
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'You are not allowed here!', 'error');
		}
		
		// create new Security class instance
		$security = new Security();
		
		// get all data from our user.add.php
		$data['username']		= $security->xss_clean($_POST['username']);
		$data['firstname']		= $security->xss_clean($_POST['firstname']);
		$data['lastname']		= $security->xss_clean($_POST['lastname']);
		$data['email']			= $security->xss_clean($_POST['email']);
		$data['password']		= encryptPassword( $_POST['password'] );
		$data['no_telefon']		= $security->xss_clean($_POST['no_telefon']);
		$data['jantina']		= $security->xss_clean($_POST['jantina']);
		$data['created']		= date('Y-m-d H:i:s');
		$data['published']		= $security->xss_clean($_POST['published']);
		
		// because we dont want this be added in our SQL query later, don't add it to $data array
		$re_password	= encryptPassword( $_POST['re-password'] );
		
		
		if ( !valid_email( $data['email'] ) ) {
			redirect(
					array(
						'controller' => 'user', 
						'action' => 'add'
					), 'E-mail not valid!', 'error');
		}
		
		// check the password, make sure both are same
		if ($data['password'] != $re_password) {
			// if not, exit and give some message to user
			redirect(array('controller' => 'user', 'action' => 'add'), 'Password not match!', 'error');
		}
		
		// create UserModel instance
		$userModel = new UserModel();
		
		// call method to save the user
		if ($userModel->create($data)) {
			// user successfully created
			redirect(array('controller' => 'user', 'action' => 'index'), 'User have been created.', 'notice');
		}
		else {
			// opsss.. something went wrong here..
			redirect(array('controller' => 'user', 'action' => 'add'), 'Error creating new user!', 'error');
		}
	}
	
	
	/**
	 * Create new user
	 */
	public function update()
	{
		if (!$this->isAdmin()) {
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'You are not allowed here!', 'error');
		}
		
		// get all data from our user.add.php
		$id						= $security->xss_clean($_POST['id']);
		//$data['username']		= $_POST['username'];
		$data['firstname']		= $security->xss_clean($_POST['firstname']);
		$data['lastname']		= $security->xss_clean($_POST['lastname']);
		$data['email']			= $security->xss_clean($_POST['email']);
		$data['no_telefon']		= $security->xss_clean($_POST['no_telefon']);
		$data['jantina']		= $security->xss_clean($_POST['jantina']);
		//$data['created']		= date('Y-m-d H:i:s');
		$data['published']		= $security->xss_clean($_POST['published']);
		
		// check if the password not empty
		if (!empty($_POST['password']) OR !empty($_POST['re-password'])) {
			
			$data['password']		= encryptPassword( $_POST['password'] );
			
			// because we dont want this be added in our SQL query later, don't add it to $data array
			$re_password	= encryptPassword( $_POST['re-password'] );
			
			// check the password, make sure both are same
			if ($data['password'] != $re_password) {
				// if not, exit and give some message to user
				redirect(array('controller' => 'user', 'action' => 'edit', 'id' => $id), 'Password not match!', 'error');
			}
		}
		
		// create UserModel instance
		$userModel = new UserModel();
		
		// call method to save the user
		if ($userModel->update($id, $data)) {
			// user successfully created
			redirect(array('controller' => 'user', 'action' => 'index'), 'User information have been updated.', 'notice');
		}
		else {
			// opsss.. something went wrong here..
			redirect(array('controller' => 'user', 'action' => 'edit', 'id' => $id), 'Error updating user!', 'error');
		}
	}
	
	
	/**
	 * Delete user from database
	 * 
	 * @param	integer		$id		Record ID
	 */
	public function del($id)
	{
		if (!$this->isAdmin()) {
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'You are not allowed here!', 'error');
		}
		
		// Make sure ID is integer
		if (!is_integer($id)) {
			// proceed
			redirect(
					array(
						'controller'	=> 'frontpage',
						'action'		=> 'index'
						), 'Invalid ID!', 'error');
		}
		
		// create UserModel instance
		$userModel = new UserModel();
		
		$result = $userModel->del($id); 
		
		if ($result) {
			// user successfully deleted
			redirect(array('controller' => 'user', 'action' => 'index'), 'User has been deleted.', 'notice');
		}
		else {
			// opsss.. something went wrong here..
			redirect(array('controller' => 'user', 'action' => 'index'), $result, 'error');
		}
	}	 	 	 
	
	
	/**
	 * Show login form
	 */
	public function login()
	{
		// load smarty from our global variable
		global $view;
		
		// set page title
		$view->assign('title', 'User Login' . ' : ' . $this->title);
		
		// load the view file
		$view->display('user.login.php');
	}
	
	
	/**
	 * Process user login
	 */
	public function process_login()
	{
		$username =	$_POST['username'];
		$password =	encryptPassword( $_POST['password'] );
		
		if (empty($username) OR empty($password)) {
			die('Username / password empty');
		}
		
		// create userModel instance
		$userModel = new UserModel();
		
		// load user data
		$user = $userModel->getUser($username);
		
		// compare user password
		if ($password === $user['password'] ) {
			// set cookie
			setcookie('is_login', 1);
			setcookie('name', $user['firstname']);
			
			$_SESSION['name']		= $user['firstname'];

			// set user_id into session
			$_SESSION['user_id']	= $user['id'];
			
			// set user_id into cookie
			setcookie('user_id', $user['id']);	

			redirect(array('controller' => 'user', 'action' => 'index'), 'Login successful');
		}
		else {
			redirect(array('controller' => 'user', 'action' => 'login'), 'Login failed', 'error');
		}
	}
	
	
	/**
	 * Logout user, remove all cookies 
	 */
	public function logout()
	{
		setcookie('is_login', '');
		setcookie('name', '');
		
		setcookie('user_id', '');
		session_destroy();
		
		redirect(array('controller' => 'user', 'action' => 'index'), 'Bye bye..');
	}
	
	
	/**
	 * View user profile
	 */
	public function profile()
	{
		global $view;
		
		// create UserModel instance
		$userModel = new UserModel();
		
		// get user profile
		$user = $userModel->getProfile();
		
		// assign to view
		$view->assign('user', $user);
		
		// set page title
		$view->assign('title', $user['firstname'] . ' ' . $user['lastname']);
		
		// load user profile view
		$view->display('user.profile.php');
	}
	
	
	/**
	 * Show editprofile view
	 */
	public function editprofile()
	{
		global $view;
		
		$userModel = new UserModel();
		
		$user = $userModel->getProfile();
		
		$view->assign('user', $user);
		
		$view->assign('title', 'Edit Profile : ' . $user['firstname'] . ' ' . $user['lastname']);
		
		$view->display('user.editprofile.php');
	}
	
	
	/**
	 * Update profile
	 */
	public function updateprofile()
	{
		$data['firstname']	= addslashes($_POST['firstname']);
		$data['lastname']	= addslashes($_POST['lastname']);
		$data['email']		= addslashes($_POST['email']);
		$data['no_telefon']	= addslashes($_POST['no_telefon']);
		$data['jantina']	= addslashes($_POST['jantina']);
		
		$id					= intval($_POST['id']);
		
		
		// check if the password not empty
		if (!empty($_POST['password']) OR !empty($_POST['re-password'])) {
			
			$data['password']		= $_POST['password'];
			
			// because we dont want this be added in our SQL query later, don't add it to $data array
			$re_password	= $_POST['re-password'];
			
			// check the password, make sure both are same
			if ($data['password'] != $re_password) {
				// if not, exit and give some message to user
				redirect(array('controller' => 'user', 'action' => 'editprofile', 'id' => $id), 'Password not match!', 'error');
			}
		}
		
		
		if (empty($_POST['firstname']) OR $_POST['firstname'] == '') {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'editprofile'
					), 'Firstname is required!', 'error');
		}
		
		// create UserModel instance
		$userModel = new UserModel();
		
		if ( $userModel->update($id, $data) ) {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'profile'
					), 'Profile updated!');
		}
		else {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'editprofile',
						'id'			=> $id
					), 'Error updating profile', 'error');
		}
	}
	
	
	/**
	 * Show change password form
	 */
	public function changepass()
	{
		global $view;
		
		$view->assign('title', 'Change password');
		$view->display('user.changepass.php');
	}
	
	
	/**
	 * Update user password
	 */
	public function updatepass()
	{
		// if old password is empty
		if ($_POST['old-password'] == '' OR empty($_POST['old-password'])) {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'changepass'
					), 'Please provide your old password', 'error');
		}
		
		// check if new password is empty
		if (empty($_POST['new-password']) OR empty($_POST['re-password'])) {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'changepass'
					), 'Please provide your new password', 'error');
		}
		
		// make sure new password and repeat password is same
		if ($_POST['new-password'] != $_POST['re-password']) {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'changepass'
					), 'Password not same!', 'error');
		}
		
		// get user id
		$id = $_SESSION['user_id'];
		
		// create UserModel instance so we can get old password
		$userModel = new UserModel();
		
		// get user
		$user = $userModel->get($id);
		
		// check if old password match with password from database
		if ( encryptPassword( $_POST['old-password'] ) == $user['password']) {
			
			// assign to $data array
			$data['password'] = encryptPassword( $_POST['new-password'] );
			
			// save to database
			$userModel->update($id, $data);
		}
		// password not same
		else {
			
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'changepass'
					), 'Invalid old password', 'error');
		}
	}
	
	
	/**
	 * Show upload avatar form
	 * 
	 * @global type $view 
	 */
	public function avatar()
	{
		global $view, $config;
		
		// assign recaptcha to view
		$view->assign('recaptcha', getReCaptcha());
		
		$view->assign('title', 'Upload avatar');
		
		$view->display('user.avatar.php');
	}
	
	
	/**
	 * Process upload image
	 * 
	 * function taken from http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html
	 * 
	 * @global type $config 
	 */
	public function uploadavatar()
	{
		global $config;
		
		//require_once LIBRARY_PATH . DS . 'recaptcha' . DS . 'recaptchalib.php';
		
		// check recaptcha
//		$resp = recaptcha_check_answer ($config['recaptcha_private_key'],
//                                $_SERVER["REMOTE_ADDR"],
//                                $_POST["recaptcha_challenge_field"],
//                                $_POST["recaptcha_response_field"]);
		
		$resp = checkReCaptcha($_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
		
		// re-captcha key not valid
		if (!$resp->is_valid) {
			redirect(
					array(
						'controller'	=> 'user',
						'action'		=> 'avatar'
					), 'Security key not valid!', 'error');
		}
		
		
		// define upload path
		$upload_path = BASE_PATH . DS . 'uploads' . DS;

		if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
			
			$image			= $_FILES['avatar']['name'];
			$uploadedfile	= $_FILES['avatar']['tmp_name'];
			
			// if we got image
			if ($image) {
				
				// get image name
				$filename	= stripslashes($_FILES['avatar']['name']);
				
				// get image extension
				$extension	= getExtension($filename);
				
				// set to lowercase
				$extension	= strtolower($extension);
				
				// check file extension, only proceed if the format is .jpg, .png and .gif
				if (($extension != 'jpg') && ($extension != 'jpeg') && ($extension != 'png') && ($extension != 'gif')) 
				{
					// nope. not valid! redirect back to user.avatar.php
					redirect(
							array(
								'controller'	=> 'user',
								'action'		=> 'avatar'
							), 'Invalid file extension! Please try with different image format.', 'error');
				}
				// yup, valid file type
				else
				{
					// get image size
					$size = filesize( $_FILES['avatar']['tmp_name'] );
					
					// make sure the image size is not bigger than allowed in our config.php
					if ($size > $config['max_size'] * 1024)
					{
						// opss... file is bigger than allowed, redirect to user.avatar.php
						redirect(
							array(
								'controller'	=> 'user',
								'action'		=> 'avatar'
							), 'Invalid file extension! Please try with different image format.', 'error');
					}

					
					// if image is jpg
					if ( $extension == 'jpg' || $extension == 'jpeg' )
					{
						// get image temp name
						$uploadedfile = $_FILES['avatar']['tmp_name'];
						
						// create new image copy in JPG format
						$src	= imagecreatefromjpeg($uploadedfile);
					}
					// if image is png
					else if ( $extension == 'png' )
					{
						// get image temp name
						$uploadedfile = $_FILES['avatar']['tmp_name'];
						
						// create new image copy in PNG format
						$src	= imagecreatefrompng( $uploadedfile );
					}
					// if image is gif
					else 
					{
						// create new image copy in GIF format
						$src	= imagecreatefromgif( $uploadedfile );
					}
					
					// get image size
					list( $width, $height ) = getimagesize( $uploadedfile );
					
					// get width from our config
					$newwidth	= $config['avatar_width'];
					
					// calculate height, so we can maintain aspect ratio
					$newheight	= ( $height / $width ) * $newwidth;
					
					// create new image
					$tmp		= imagecreatetruecolor($newwidth, $newheight);
					
					// Copy and resize part of an image with resampling
					imagecopyresampled( $tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
					
					// get image name
					$image_name = md5($_FILES['avatar']['name']) . '.' . $extension;
					
					//$filename = BASE_PATH . DS . 'uploads' . DS . $_FILES['avatar']['name'];
					$filename = BASE_PATH . DS . 'uploads' . DS . $image_name;
					
					// create JPG format
					imagejpeg( $tmp, $filename, 100 );
					
					// remove temporary image
					imagedestroy( $src );
					imagedestroy( $tmp );
					
					$data['avatar'] = $image_name;
					
					// create usermodel instance
					$userModel = new UserModel();
					
					// update to database
					$userModel->update($_SESSION['user_id'], $data);
					
					// redirect to profile page
					redirect(
							array(
								'controller'	=> 'user',
								'action'		=> 'profile'
							), 'Image uploaded successfully!');
				}
			}
		}
	}
}